package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.HosptialInfoAdapter;
import com.xn.app.muying.bean.HosptialInfoListBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 医院咨询
 * Created by Administrator on 2016/11/7.
 */
public class HosptialActivity extends BaseActivity implements HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener, MyListView.IXListViewListener {
    private Handler handler = new Handler();
    private HosptialInfoAdapter hosptialInfoAdapter;
    private ArrayList<HosptialInfoListBean> list = new ArrayList<>();
    ;
    //数据显示
    private MyListView listview = null;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog dialog;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    String antenatalCareHospitalId = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hosptial);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        listview = (MyListView) findViewById(R.id.activity_hosptial_listview);
        findViewById(R.id.hosptial_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        antenatalCareHospitalId = getIntent().getStringExtra("antenatalCareHospitalId");

        listview.setOnItemClickListener(this);

        hosptialInfoAdapter = new HosptialInfoAdapter(HosptialActivity.this, imageLoader, options);
        listview.setAdapter(hosptialInfoAdapter);
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(HosptialActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            HttpUtil.getData(APIMethod.HosptialList(antenatalCareHospitalId, currentPage, number), handler, this);
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "医院咨询");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            if (totalCount == 0) {
                totalCount = jsonObject.getInt("totalCount");
            }
            JSONArray items = jsonObject.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String title = object.optString("title");
                String pictureUrl = object.optString("pictureUrl");
                String creationTime = object.optString("creationTime");
                String id = object.optString("id");
                HosptialInfoListBean hosptialInfoListBean = new HosptialInfoListBean();
                hosptialInfoListBean.setTitle(title);
                hosptialInfoListBean.setPictureUrl(pictureUrl);
                hosptialInfoListBean.setCreationTime(creationTime);
                hosptialInfoListBean.setId(id);
                list.add(hosptialInfoListBean);

            }
            onLoad();
            listview.setPullLoadEnable(true);
            listview.setXListViewListener(HosptialActivity.this, totalCount, currentPage, number);
            hosptialInfoAdapter.getData(list);
            if (listview.getVisibility() == View.GONE) {
                listview.setVisibility(ListView.VISIBLE);
            }
            dialog.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent();
        intent.putExtra("type", 0);
        intent.putExtra("id", list.get(i).getId());
        intent.putExtra("name", list.get(i).getTitle());
        intent.setClass(HosptialActivity.this, EducationDetailsActivity.class);
        startActivity(intent);
    }

    //上拉加载
    @Override
    public void onLoadMore() {
        if (NetworkUtil.isNetworkAvailable(HosptialActivity.this)) {
            if (totalCount > currentPage * number) {
                currentPage = currentPage + 1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(AppConstant.THREAD_SLEEP);
                            HttpUtil.getData(APIMethod.HosptialList(antenatalCareHospitalId, currentPage, number), handler, HosptialActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                onLoad();
            }
        } else {
            onLoad();
            ToastUtil.showToast(HosptialActivity.this, R.string.no_network_hint);
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
